<template>
  <!-- <bread-crumb></bread-crumb>
  <x-card
    :message="message_card"
    :width="98"
    :height="height"
    style="margin: 20px 20px"
  > -->
  <!-- 搜索以及操作 -->
  <!-- 自定义组件 -->
  <x-search>
    <!-- 搜索的一系列东西 -->
    <template #search>
      <p>
        权限名称
        <a-input
          v-model:value="permis_name"
          placeholder="请输入权限名称"
          style="width: 150px"
        />
      </p>
      <p style="margin-left: 10px">
        权限标识
        <a-input
          v-model:value="permis_sign"
          placeholder="请输入权限标识"
          style="width: 150px"
        />
      </p>
      <a-button type="primary" style="margin-left: 10px" @click="but_search"
        >搜索</a-button
      >
      <a-button style="margin-left: 10px" @click="reset_search">重置</a-button>
    </template>
    <!-- 操作的一系列东西 -->
    <template #operate>
      <a-button
        type="primary"
        style="margin-left: 10px"
        @click="showModal_add"
        v-checkpermission:foo.bar="'system_permiss_add'"
        ><template #icon><plus-outlined style="margin-right: 0" /></template
        >新增权限</a-button
      >
    </template>
  </x-search>
  <!-- 谈话框--添加权限 -->
  <a-modal v-model:open="open_add" title="新增权限" @ok="handleOk">
    <a-form
      ref="formRef"
      :model="formState"
      :rules="rules"
      :label-col="labelCol"
      :wrapper-col="wrapperCol"
    >
      <a-form-item label="父级权限" name="father">
        <a-select v-model:value="formState.father" placeholder="请选择父级权限(若无选最高级)">
          <a-select-option
            v-for="(value, index) in all_permises"
            :key="index"
            :value="value.id"
            >{{ value.name }}</a-select-option
          >
        </a-select>
      </a-form-item>

      <a-form-item label="权限名称" name="name">
        <a-input v-model:value="formState.name" placeholder="请输入权限名称" />
      </a-form-item>

      <a-form-item label="权限标识" name="sign">
        <a-input v-model:value="formState.sign" placeholder="请输入权限标识" />
      </a-form-item>

      <a-form-item label="权限类型" name="type">
        <!-- 0 菜单；1 按钮 -->
        <a-radio-group v-model:value="formState.type">
          <a-radio :value="0">菜单</a-radio>
          <a-radio :value="1">按钮</a-radio>
          <a-radio :value="2">页面</a-radio>
        </a-radio-group>
      </a-form-item>

      <a-form-item label="路由路径" name="router_url">
        <a-input
          v-model:value="formState.router_url"
          placeholder="请输入权限路由路径"
        />
      </a-form-item>

      <a-form-item label="组件路径" name="component_url">
        <a-input
          v-model:value="formState.component_url"
          placeholder="请输入权限组件路径"
        />
      </a-form-item>

      <a-form-item label="图标" name="icon">
        <a-input
          v-model:value="formState.icon"
          placeholder="请输入权限图标路径"
        />
      </a-form-item>

      <a-form-item label="排序" name="sort">
        <a-form-item name="sort" no-style>
          <a-input-number v-model:value="formState.sort" :min="0" :max="10" />
        </a-form-item>
      </a-form-item>
    </a-form>
  </a-modal>
  <!-- 搜索下面的表格 -->
  <a-table
    :dataSource="dataSource"
    :columns="columns"
    :loading="loading"
    :row-selection="{
      selectedRowKeys: state.selectedRowKeys,
      onChange: onSelectChange,
    }"
    :pagination="{
      pageSize: state.pageSize,
      total: state.total,
      current: state.current,
      showSizeChanger: true, // 显示每页条数选择器
      pageSizeOptions: ['25', '50', '100'], // 自定义每页条数选项
      showTotal: (total:number) => `共 ${total} 条`, // 显示总条数
    }"
    @change="
      (pagination:any) => {
        console.log(pagination);
        state.pageSize = pagination.pageSize;
        state.total = pagination.total;
        state.current = pagination.current;
        permis_list();
      }
    "
    :scroll="{ y: 600 }"
    :defaultExpandAllRows="true"
    childrenColumnName="children"
    v-checkpermission:foo.bar="'system_permiss_list'"
  >
    <!-- :columns="columns" :data-source="data" @resizeColumn="handleResizeColumn" -->
    <!-- 头部表头默认显示，不需要操作 -->
    <!-- <template #headerCell="{ column }"></template> -->
    <!-- 身体-表格中的列表 -->
    <!-- <template #bodyCell="{ column, record }"> -->
    <template #bodyCell="{ column, record }">
      <template v-if="column.key === 'role_name'">
        <!-- {{ record }} -->
        <span>
          <!-- hhh -->
          <button
            style="
              border: none;
              background-color: #f4f4f5;
              border-radius: 5px;
              color: #92969b;
            "
          >
            {{ record.role_name }}
          </button>
          <!-- <p>{{ record.role_name }}</p> -->
        </span>
      </template>
      <template v-if="column.key === 'type'">
        <a-tag v-if="record.type === 0" color="#2db7f5"> 菜单类型 </a-tag>
        <a-tag v-if="record.type === 1" color="#87d068"> 按钮类型 </a-tag>
        <a-tag v-if="record.type === 2" color="#108ee9"> 页面类型 </a-tag>
      </template>
      <template v-else-if="column.key === 'action'">
        <a-space>
          <!-- 编辑按钮 -->
          <a-tooltip title="编辑" placement="top">
            <a-button
              type="text"
              size="small"
              @click="showModal_edit(record.id)"
              v-checkpermission:foo.bar="'system_permiss_edit'"
            >
              <template #icon>
                <EditOutlined style="color: #1890ff" />
              </template>
            </a-button>
          </a-tooltip>

          <!-- 添加子选项按钮 -->
          <a-tooltip title="添加子选项" placement="top">
            <a-button
              type="text"
              size="small"
              @click="add_permiseson(record.id)"
              v-checkpermission:foo.bar="'system_permiss_add'"
            >
              <template #icon>
                <PlusOutlined style="color: #52c41a" />
              </template>
            </a-button>
          </a-tooltip>

          <!-- 状态切换按钮 -->
          <a-tooltip
            :title="record.state === 0 ? '禁用' : '启用'"
            placement="top"
          >
            <a-button
              type="text"
              size="small"
              :danger="record.state === 0"
              @click="
                record.state === 0
                  ? del_user_f(record.id)
                  : state_start(record.id)
              "
              v-checkpermission:foo.bar="'system_permiss_delete'"
            >
              <template #icon>
                <DeleteOutlined
                  :style="{ color: record.state === 0 ? '#ff4d4f' : '#52c41a' }"
                />
              </template>
            </a-button>
          </a-tooltip>

          <!-- 真删除按钮 -->
          <a-tooltip v-if="record.state === 1" title="删除" placement="top">
            <a-button
              type="text"
              size="small"
              danger
              @click="del_user_t(record.id)"
              v-checkpermission:foo.bar="'system_permiss_delete'"
            >
              <template #icon>
                <DeleteOutlined style="color: #cf1322" />
              </template>
            </a-button>
          </a-tooltip>
        </a-space>
      </template>
    </template>
  </a-table>
  <!-- 谈话框--编辑权限 -->
  <a-modal v-model:open="open_edit" title="修改权限" @ok="handleOk_edit">
    <a-form
      ref="formRef_edit"
      :model="formState_edit"
      :rules="rules"
      :label-col="labelCol"
      :wrapper-col="wrapperCol"
    >
      <a-form-item label="父级权限" name="father">
        <a-select
          v-model:value="formState_edit.father"
          :placeholder="
            formState_edit.father == 0 ? '最高级权限' : '请选择父级权限'
          "
          :disabled="formState_edit.father == 0"
        >
          <template v-if="formState_edit.father == 0">
            <a-select-option :value="0">最高级权限</a-select-option>
          </template>
          <template v-else>
            <a-select-option
              v-for="item in all_permises"
              :key="item.id"
              :value="item.id"
            >
              {{ item.name }}
            </a-select-option>
          </template>
        </a-select>
      </a-form-item>

      <a-form-item label="权限名称" name="name">
        <a-input v-model:value="formState_edit.name" />
      </a-form-item>

      <a-form-item label="权限标识" name="sign">
        <a-input v-model:value="formState_edit.sign" />
      </a-form-item>

      <a-form-item label="权限类型" name="type">
        <!-- 0 菜单；1 按钮 -->
        <a-radio-group v-model:value="formState_edit.type">
          <a-radio :value="0">菜单</a-radio>
          <a-radio :value="1">按钮</a-radio>
          <a-radio :value="2">页面</a-radio>
        </a-radio-group>
      </a-form-item>

      <a-form-item label="路由路径" name="router_url">
        <a-input v-model:value="formState_edit.router_url" />
      </a-form-item>

      <a-form-item label="组件路径" name="component_url">
        <a-input v-model:value="formState_edit.component_url" />
      </a-form-item>

      <a-form-item label="图标" name="icon">
        <a-input v-model:value="formState_edit.icon" />
      </a-form-item>

      <a-form-item label="排序" name="sort">
        <a-form-item name="sort" no-style>
          <a-input-number
            v-model:value="formState_edit.sort"
            :min="0"
            :max="10"
          />
        </a-form-item>
      </a-form-item>
    </a-form>
  </a-modal>
  <!-- 谈话窗--添加子项 -->
  <a-modal v-model:open="open_son" title="新增子权限" @ok="handleOk_son">
    <a-form
      ref="formRef_son"
      :model="formState_son"
      :rules="rules"
      :label-col="labelCol"
      :wrapper-col="wrapperCol"
    >
      <a-form-item label="父级权限" name="father">
        <a-select
          v-model:value="formState_son.father"
          placeholder="请选择父级权限"
          :disabled="true"
        >
          <a-select-option
            v-for="(value, index) in all_permises"
            :key="index"
            :value="value.id"
            >{{ value.name }}</a-select-option
          >
        </a-select>
      </a-form-item>

      <a-form-item label="权限名称" name="name">
        <a-input v-model:value="formState_son.name" />
      </a-form-item>

      <a-form-item label="权限标识" name="sign">
        <a-input v-model:value="formState_son.sign" />
      </a-form-item>

      <a-form-item label="权限类型" name="type">
        <!-- 0 菜单；1 按钮 -->
        <a-radio-group v-model:value="formState_son.type">
          <a-radio :value="0">菜单</a-radio>
          <a-radio :value="1">按钮</a-radio>
          <a-radio :value="2">页面</a-radio>
        </a-radio-group>
      </a-form-item>

      <a-form-item label="路由路径" name="router_url">
        <a-input v-model:value="formState_son.router_url" />
      </a-form-item>

      <a-form-item label="组件路径" name="component_url">
        <a-input v-model:value="formState_son.component_url" />
      </a-form-item>

      <a-form-item label="图标" name="icon">
        <a-input v-model:value="formState_son.icon" />
      </a-form-item>

      <a-form-item label="排序" name="sort">
        <a-form-item name="sort" no-style>
          <a-input-number
            v-model:value="formState_son.sort"
            :min="0"
            :max="10"
          />
        </a-form-item>
      </a-form-item>
    </a-form>
  </a-modal>
  <!-- </x-card> -->
</template>

<script lang="ts" setup>
import XSearch from "./XSearch.vue";
import { ref, reactive, toRaw, onMounted, createVNode } from "vue";
import http from "../routerutils/http";
import { message, Modal, Cascader } from "ant-design-vue";
// 对话提示
import {
  EditOutlined,
  PlusOutlined,
  DeleteOutlined,
  ExclamationCircleOutlined,
} from "@ant-design/icons-vue";
// 表单验证
import type { Rule } from "ant-design-vue/es/form";
import type { UnwrapRef } from "vue";
import type { CascaderProps } from "ant-design-vue";
import { number } from "echarts";
import { useStore } from "vuex";
const store = useStore();
const userPermiss_vuex = store.state.userPermiss;
// 创建一个自定义指令，来统一处理权限存在与否
const vCheckpermission = {
  mounted: (el: any, binding: any) => {
    if (!userPermiss_vuex.includes(binding.value)) {
      // 移除元素
      el.parentNode?.removeChild(el);
    }
    console.log(el, binding);
    // el.classList.add("is-highlight");
  },
};

// x-card组件中的属性值
const message_card = ref<string>("");
const height = ref<string>("850px");
// 1. 搜索相关的操作数据
const permis_name = ref<string>("");
const permis_sign = ref<string>("");
// 重置按钮的方法
const reset_search = () => {
  state.current = 1;
  permis_name.value = "";
  permis_sign.value = "";
  permis_list();
};
// 搜索按钮的方法
const but_search = () => {
  permis_list();
  state.current = 1;
};
// 2. 新增权限按钮的相关操作
// 谈话窗是否展示
const open_add = ref<boolean>(false);
const labelCol = { span: 5 };
const wrapperCol = { span: 13 };
const formRef = ref();
// 添加权限接口
const add_role = async () => {
  try {
    const response = await http.post("/api/permissions/add ", {
      name: formState.name,
      father: formState.father,
      sign: formState.sign,
      type: formState.type,
      router_url: formState.router_url,
      component_url: formState.component_url,
      icon: formState.icon,
      sort: formState.sort,
    });
    console.log("添加权限：", response);
    const msg = response.data.msg;
    message.success(msg);
    permis_list();
    all_permis();
  } catch (error) {
    console.log("请求失败：：", error);
  }
};
// 接口--修改和添加用一样的接口
interface FormState {
  name: string;
  father: number;
  sign: string;
  type: number;
  router_url: string;
  component_url: string;
  icon: string;
  sort: number;
}
// 表单元素
const formState: UnwrapRef<FormState> = reactive({
  name: "",
  father: null,
  sign: "",
  type: null,
  router_url: "",
  component_url: "",
  icon: "",
  sort: 0,
});
// 规则--修改和添加用一样的接口
const rules: Record<string, Rule[]> = {
  name: [
    { required: true, message: "请输入权限名字", trigger: "change" },
    { min: 2, max: 10, message: "长度为2到10个字符串", trigger: "blur" },
  ],
  father: [{ required: true, message: "请选择父级", trigger: "change" }],
  sign: [
    { required: true, message: "请输入权限标识", trigger: "change" },
    { min: 3, message: "长度最少为3个字符串", trigger: "blur" },
  ],
  type: [
    {
      required: true,
      message: "请选择权限类型",
      trigger: "change",
    },
  ],
  router_url: [
    { required: true, message: "请输入权限标识", trigger: "change" },
    { min: 3, message: "长度最少为3个字符串", trigger: "blur" },
  ],
  component_url: [
    { required: true, message: "请输入权限标识", trigger: "change" },
    { min: 3, message: "长度最少为3个字符串", trigger: "blur" },
  ],
  icon: [
    { required: true, message: "请输入权限标识", trigger: "change" },
    { min: 3, message: "长度最少为3个字符串", trigger: "blur" },
  ],
};
// 添加按钮
const showModal_add = () => {
  open_add.value = true;
};
// 对话窗中的确定按钮
const handleOk = () => {
  formRef.value
    .validate()
    .then(() => {
      console.log("values", formState, toRaw(formState));
      open_add.value = false;
      // 添加权限的接口
      add_role();
    })
    .catch((error) => {
      console.log("error", error);
    });
};
// 所有权限id接口
interface permiseRole {
  id: number;
  name: string;
}
const all_permises = ref<permiseRole[]>([]);
const all_permis = async () => {
  try {
    const response = await http.get("/api/permissions/all");
    console.log(response);
    all_permises.value = response.data.results;
    const highest_permiss = {
      id: 0,
      name: "最高级权限",
    };
    // unshift加到前面
    all_permises.value.unshift(highest_permiss);
  } catch (error) {
    console.log("请求失败：", error);
  }
};
// 3. 表格中的一系列操作及数据
type Key = string | number;
const loading = ref<boolean>(false);
// 表头
const columns = [
  {
    title: "权限名称",
    dataIndex: "name",
    key: "name",
    width: 120,
  },
  {
    title: "权限标识",
    dataIndex: "sign",
    key: "sign",
    width: 120,
  },
  {
    title: "权限类型",
    dataIndex: "type",
    key: "type",
    width: 120,
  },
  {
    title: "路由路径",
    dataIndex: "router_url",
    key: "router_url",
    width: 120,
  },
  {
    title: "组件路径",
    dataIndex: "component_url",
    key: "component_url",
    width: 200,
  },
  {
    title: "操作",
    key: "action",
    width: 150,
  },
];
// 表中数据
const dataSource = ref<TreeNode[]>([]);
// 勾选框的一系列操作
const state = reactive<{
  selectedRowKeys: Key[];
  loading: boolean;
  pageSize: number;
  total: number;
  current: number;
}>({
  selectedRowKeys: [],
  loading: false,
  pageSize: 30,
  total: 100,
  current: 1,
});
// 勾选时候的事件
const onSelectChange = (selectedRowKeys: Key[]) => {
  console.log("selectedRowKeys changed: ", selectedRowKeys);
  state.selectedRowKeys = selectedRowKeys;
};
// 将扁平权限列表转换为树形结构
interface Permission {
  id: number;
  father: number;
  name: string;
  sign: string;
  type: number;
  router_url: string;
  component_url: string;
  icon: string;
  sort: number;
}
interface TreeNode {
  key: number;
  name: string;
  // 保留原始权限的所有字段
  [key: string]: any;
  children?: TreeNode[];
}
const processPermissions = (permissions: Permission[], parentKey: string = ''): any[] => {
  return permissions.map((item, index) => {
    // 生成唯一key（格式：父key-当前索引，如 "0-1-2"）
    const currentKey = parentKey ? `${parentKey}-${index+1}` : `${index+1}`;
    
    return {
      ...item,
      key: currentKey, // Ant Design表格需要的key
      title: item.name,
      children: item.children?.length 
        ? processPermissions(item.children, currentKey) // 递归处理子级
        : undefined,
    };
  });
};
// 请求后端列表接口
const permis_list = async () => {
  try {
    loading.value = true; // 开始加载
    const response = await http.get("/api/permissions/list", {
      params: {
        name: permis_name.value.trim(),
        sign: permis_sign.value.trim(),
        page_size: state.pageSize,
        page: state.current,
      },
    });
    dataSource.value = processPermissions(response.data.results.permissions);
    console.log("处理后的数据：",dataSource.value)

    state.total = response.data.results.total;
  } catch (error) {
    console.log("请求失败：：", error);
  } finally {
    loading.value = false; // 开始加载
  }
};
// 4. 修改权限一系列操作
// 修改权限--保存数据
const edit_id = ref<number>(); // 修改的id
// 表单元素
const formState_edit: UnwrapRef<FormState> = reactive({
  name: "",
  father: null,
  sign: "",
  type: null,
  router_url: "",
  component_url: "",
  icon: "",
  sort: 0,
});
// 修改-设置数据接口
const edit_save = async () => {
  try {
    const response = await http.post("/api/permissions/set", {
      id: edit_id.value,
      name: formState_edit.name,
      father: formState_edit.father,
      sign: formState_edit.sign,
      type: formState_edit.type,
      router_url: formState_edit.router_url,
      component_url: formState_edit.component_url,
      icon: formState_edit.icon,
      sort: formState_edit.sort,
    });
    console.log(response);
    const msg = response.data.msg;
    message.success(msg);
    permis_list();
    all_permis();
  } catch (error) {
    console.log("请求失败：：", error);
  }
};
// 弹窗的关闭与否
const open_edit = ref<boolean>(false);
const formRef_edit = ref();

// 打开谈话窗的按钮方法// 修改权限--获取数据
const showModal_edit = async (id: number) => {
  // console.log(id)
  open_edit.value = true;
  try {
    const response = await http.get("/api/permissions/get", {
      params: {
        id: id,
      },
    });
    formState_edit.name = response.data.results[0].name;

    // if (response.data.results[0].father == 0) {
    //   formState_edit.father = "最高级权限";
    // }
    formState_edit.father = response.data.results[0].father;
    formState_edit.sign = response.data.results[0].sign;
    formState_edit.type = response.data.results[0].type;
    formState_edit.router_url = response.data.results[0].router_url;
    formState_edit.component_url = response.data.results[0].component_url;
    formState_edit.icon = response.data.results[0].icon;
    formState_edit.sort = response.data.results[0].sort;
    edit_id.value = response.data.results[0].id;
    console.log(response);
  } catch (error) {
    console.log("请求失败：：", error);
  }
};
// 谈话框中点击确定的时候方法
const handleOk_edit = () => {
  formRef_edit.value
    .validate()
    .then(() => {
      console.log("values", formState_edit, toRaw(formState_edit));
      open_edit.value = false;
      // 修改权限--保存数据
      edit_save();
    })
    .catch((error) => {
      console.log("error", error);
    });
};
// 5. 删除权限-软删除
const del_user_f = (id: number) => {
  // 删除权限的对话框
  Modal.confirm({
    title: "禁用权限",
    icon: createVNode(ExclamationCircleOutlined),
    content: "您确定要禁用此权限吗？",
    okText: "确定",
    okType: "danger",
    cancelText: "取消",
    async onOk() {
      console.log("OK");
      // 删除的接口
      try {
        const response = await http.get("/api/permissions/del_f", {
          params: {
            id: id,
          },
        });
        console.log(response);
        const msg = response.data.msg;
        message.success(msg);
        // 删除成功时候调用列表
        permis_list();
        all_permis();
      } catch (error) {
        console.log("请求失败：：", error);
      }
    },
    onCancel() {
      console.log("Cancel");
    },
  });
};
const state_start = async (id: number) => {
  try {
    const response = await http.get("/api/permissions/start", {
      params: {
        id: id,
      },
    });
    console.log(response);
    const msg = response.data.msg;
    if (response.data.code === 1) {
      message.error(msg);
    } else {
      message.success(msg);
    }
    // 删除成功时候调用列表
    permis_list();
    all_permis();
  } catch (error) {
    console.log("请求失败：：", error);
  }
};
// 6. 删除权限-真删除
const del_user_t = (id: number) => {
  // 删除权限的对话框
  Modal.confirm({
    title: "删除权限",
    icon: createVNode(ExclamationCircleOutlined),
    content: "您确定要删除此权限吗？",
    okText: "确定",
    okType: "danger",
    cancelText: "取消",
    async onOk() {
      console.log("OK");
      // 删除的接口
      try {
        const response = await http.get("/api/permissions/del_t", {
          params: {
            id: id,
          },
        });
        console.log(response);
        const msg = response.data.msg;
        message.success(msg);
        // 删除成功时候调用列表
        permis_list();
        all_permis();
      } catch (error) {
        console.log("请求失败：：", error);
      }
    },
    onCancel() {
      console.log("Cancel");
    },
  });
};
// 7. 谈话窗--添加子项
// 添加子选项的父选项id
// const father_id = ref<number>()
// 添加子选项接口
const handleOk_son = async () => {
  try {
    const response = await http.post("/api/permissions/add_son", {
      name: formState_son.name,
      father: formState_son.father,
      sign: formState_son.sign,
      type: formState_son.type,
      router_url: formState_son.router_url,
      component_url: formState_son.component_url,
      icon: formState_son.icon,
      sort: formState_son.sort,
    });
    open_son.value = false;
    permis_list();
    all_permis();
    reset_son();
    const msg = response.data.msg;
    message.success(msg);
  } catch (error) {
    console.log("请求失败：：", error);
  }
};
// 谈话框是否显示
const open_son = ref<boolean>(false);
const formRef_son = ref();
// 表单元素
const formState_son: UnwrapRef<FormState> = reactive({
  name: "",
  father: null,
  sign: "",
  type: null,
  router_url: "",
  component_url: "",
  icon: "",
  sort: 0,
});
const reset_son = () => {
  formState_son.name = "";
  formState_son.father = null;
  formState_son.sign = "";
  formState_son.type = null;
  formState_son.router_url = "";
  formState_son.component_url = "";
  formState_son.icon = "";
  formState_son.sort = 0;
};
// 添加子选项-按钮
const add_permiseson = (id: number) => {
  // console.log("id:::",id)
  formState_son.father = id;
  // father_id.value = id
  open_son.value = true;
};
// 对话框中的确定按钮
// 声明周期函数
onMounted(() => {
  all_permis();
  permis_list();
});
</script>

<style scoped>
:deep(:where(.css-dev-only-do-not-override-1p3hq3p).ant-btn > .anticon + span),
:deep(:where(.css-dev-only-do-not-override-1p3hq3p).ant-btn > span + .anticon) {
  margin-inline-start: 0px;
}
</style>